package helper

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	time2 "time"
)

var ctx = context.Background()
var rdb *redis.Client

func InitRedisHelper() error {
	rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	_, err := rdb.Ping(ctx).Result()
	return err
}

func RedisHelper() *redis.Client {
	return rdb
}

//get
func RedisHelperGet(key string) string {
	result, err := rdb.Get(ctx, key).Result()
	if err != nil {
		fmt.Println(err)
	}
	return result
}

//set
func RedisHelperSet(key, value string, second time2.Duration) {
	err := rdb.Set(ctx, key, value, second*time2.Second).Err()
	if err != nil {
		fmt.Println(err)
	}
}

//判断是否存在
func RedisHelperExists(keys ...string) int64 {
	result, err := rdb.Exists(ctx, keys...).Result()
	if err != nil {
		fmt.Println(err)
	}
	return result
}

//删除
func RedisHelperDelete(keys ...string) int64 {
	result, err := rdb.Del(ctx, keys...).Result()
	if err != nil {
		fmt.Println(err)
	}
	return result
}

//过期剩余时间
func RedisHelperTtl(key string) time2.Duration {
	result, err := rdb.TTL(ctx, key).Result()
	if err != nil {
		fmt.Println(err)
	}
	return result
}
